package com.pks.datacenter.service.api;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.pks.datacenter.config.RedisKeyConfig;
import com.pks.datacenter.entity.api.ApiUser;
import com.pks.datacenter.handler.RedisHandler;
import com.pks.datacenter.mapper.api.ApiUserMapper;
import com.pks.resultful.common.SRemoteResult;
import com.pks.web.mybatis.service.BasicServiceImpl;

@Component("apiUserService")
public class ApiUserServiceImpl extends BasicServiceImpl<ApiUser, Long, ApiUserMapper> implements ApiUserService {

	@Autowired
	private ApiUserMapper apiUserMapper;
	@Autowired
	private RedisHandler redisHandler;

	@Override
	protected ApiUserMapper getMapper() {
		return apiUserMapper;
	}

	@Override
	public ApiUser findById(Long id) {
		ApiUser apiUser = null;
		Object obj = redisHandler.get(RedisKeyConfig.KEY_INFO_APIUSER_PREFIX + id);
		if (obj != null) {
			apiUser = (ApiUser) obj;
		} else {
			apiUser = apiUserMapper.findById(id);
			redisHandler.set(RedisKeyConfig.KEY_INFO_APIUSER_PREFIX + id, apiUser , RedisKeyConfig.CACHE_TIME);
		}
		return apiUser;
	};
	
	@Override
	public SRemoteResult<String> updateForResetPwd(Long id, String pwd) {
		ApiUser apiUser = findById(id);
		if (apiUser == null) {
			return SRemoteResult.initErrorDataNone();
		}
		ApiUser update = new ApiUser();
		update.setId(id);
		update.setPassword(pwd);
		apiUserMapper.updateOfChange(update);
		redisHandler.del(RedisKeyConfig.KEY_INFO_APIUSER_PREFIX + id);
		return SRemoteResult.initSuccess(pwd);
	}

	@Override
	public SRemoteResult<String> insertOrModify(ApiUser obj) {
		if (obj != null) {
			if (obj.getId() == null) {
				obj.insertBefore();
				apiUserMapper.insert(obj);
			} else {
				ApiUser update = apiUserMapper.findById(obj.getId());
				if (update == null) {
					return SRemoteResult.initErrorDataNone();
				}
				apiUserMapper.update(obj);
			}
			redisHandler.del(RedisKeyConfig.KEY_INFO_APIUSER_PREFIX + obj.getId());
		}
		return SRemoteResult.initSuccess(null);
	}

	@Override
	public void deleteApiUsers(List<Long> ids) {
		if (ids != null && ids.size() > 0) {
			if (ids.size() == 1) {
				apiUserMapper.delete(ids.get(0));
			} else {
				apiUserMapper.deleteByIds(ids);
			}
			for (Long id : ids) {
				redisHandler.del(RedisKeyConfig.KEY_INFO_APIUSER_PREFIX + id);
			}
		}
	}
	
	
}
